package com.opal.filter;

import com.opal.consts.CommonConst;
import com.opal.consts.WSC;
import com.opal.utils.CommonUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest)request;
        HttpServletResponse res= (HttpServletResponse)response;
        //获取session
        Object user = req.getSession().getAttribute(CommonConst.OPALUSER);
        String uri = req.getRequestURI();
        int i = uri.indexOf("login");
        int i2=uri.indexOf("jquery"); //登录页面需要jquery

        if(user ==null && (i <0 && i2<0 && !uri.equals("/")) ){
            //获取是否异步
           boolean bool= CommonUtils.isAjaxRequest((HttpServletRequest) request);
            if(!bool) {
                res.setContentType("text/html;charset=UTF-8");
                res.getWriter().write("<script>\n" +
                        "\t\t\tvar bol=window.confirm(\"登录已过期！\")\n" +
                        "\t\t\tif(bol){\n" +
                        "\t\t\t\twindow.location.href=\"/user/login.html\";\n" +
                        "\t\t\t}\n" +
                        "\t\t</script>");
            }else {
                res.setContentType("application/json;charset=UTF-8");
                res.getWriter().write("{\"statu\":"+ WSC.REQUEST_UNAUTHORIZED +",\"message\":\"登录已过期，请重新登录！\",\"code\":\"1\",\"msg\":\"登录已过期，请重新登录！\"}"); //异步需要自己判断 "code":0,"msg":""是layui的table提示用
            }
        }else {
            chain.doFilter(request,response);
            //重写了响应需要自行处理数据返回给浏览器
//            chain.doFilter(request,resp);
//            byte[] content = resp.getContent();
//            String str;
//            if (content.length > 0){
//                str= new String(content,"utf-8");
//                System.out.println("返回值:" + str);
//                //把参数返回值输出到客户端
//                ServletOutputStream out = response.getOutputStream();
//                out.write(str.getBytes());
//                out.flush();
//            }
        }
    }
}
